// components/PFEP_components/pfep_login_dialog/login_dialog.js
const mybehavior = require('../../../behaviors/requests')
Component({
  behaviors: [mybehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    ID: "",
    password: "",
    base_url: 'https://logisticsengineering.gree.com',
    beforeClose: {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onBeforeClose(action) {
      return new Promise((resolve) => {
        if (action === 'confirm') {
          let url = this.data.base_url + "/pfep_api/login_manage/login"
          let data = {
            ID: this.data.ID,
            password: this.data.password
          }

          this.post(url, data).then(res => {
            if (res.code == 20000) {
              const data = res.data;
              const token = data["token"];
              const username = data["name"];
              wx.setStorageSync('pfep_token', token);
              wx.setStorageSync('pfep_username', username);
              wx.setStorageSync('pfep_id', JSON.stringify(data._id));
              this.triggerEvent("ChangeUserName", username);
              resolve(true);
            } else {
              wx.showToast({
                title: res.msg,
                icon: 'error'
              })
              resolve(false)
            }
          }).catch(err => {
            if (err.code == 50006) {
              resolve(true)
              //将用户ID信息存储起来确保后面注册时能顺利调用
              wx.setStorageSync('ID', this.data.ID)
              //显示注册页面,关闭登录页面显示
              this.triggerEvent("LoginControl", {
                showLogin: false,
                showRegister: true
              })
            } else if (err.msg) {
              wx.showToast({
                title: err.msg,
                icon: 'none'
              })
              resolve(false)
            } else {
              wx.showToast({
                title: "服务器出错了",
                icon: 'none'
              })
              resolve(true)
            }
          })
        } else {
          // 拦截取消操作,无登录信息就跳出去，不让进行下一步操作
          let pfep_id = wx.getStorageSync('pfep_id')
          resolve(true)
          if (!pfep_id) {
            wx.navigateTo({
              url: "/pages/nav/pfep/nav_pfep",
            })
          }
        }
      })
    },
  },
  lifetimes: {
    // 组件实例进入节点树
    attached() {
      var that = this
      that.setData({
        beforeClose: (action) => this.onBeforeClose(action)
      })
      let pfep_id = wx.getStorageSync('pfep_id')
      let pfep_username = wx.getStorageSync('pfep_username')
      if (!pfep_id) {
        this.triggerEvent("LoginControl", {
          showLogin: true,
          showRegister: false
        })
      }else{
         this.triggerEvent("ChangeUserName",pfep_username)
      }
    }
  }
})